package com.c.status_machine;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.tool.ToolRedisson;
import ntd.util.ToolLock;
import ntd.util.fun.ComFun;

import java.time.Duration;

/**
 * @author: liuwenju
 * @date: 2023/8/2 14:38
 * @version: 1.0
 */
public class StatusJedis {

    private String key;
    private ComFun.FunInNoException<String> inNoException;

    public StatusJedis(String key, ComFun.FunInNoException<String> inNoException) {
        this.key = gen_key(key);
        this.inNoException = inNoException;
    }

    public void setStatus(String t) {
        ToolLock.lockRun(key, () -> {
            String old_str = ToolRedisson.me.get(key);
            String new_str = JSONUtil.toJsonStr(t);
            if (!StrUtil.equals(old_str, new_str)) {
                inNoException.accept(new_str);
            }
            ToolRedisson.me.set(key, new_str, Duration.ofSeconds(20));
        });
    }

    public String getStatus() {
        return ToolRedisson.me.get(key);
    }

    private String gen_key(String key) {
        return "com:status:jedis:" + key;
    }
}
